package com.lingyun.mqttserver.handler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lingyun.mqttserver.dao.mapper.DeviceInfoMapper;
import com.lingyun.mqttserver.dao.pojo.DeviceInfo;
import com.lingyun.mqttserver.service.ModbusCommandService;
import com.lingyun.mqttserver.service.impl.MqttMessageService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * 测试主题专用消息处理器
 */
@Component
public class TestTopicMessageHandler implements MessageHandler {

    @Autowired
    private MqttMessageService mqttMessageService;

    @Autowired
    private ModbusCommandService modbusCommandService;

    @Autowired
    private DeviceInfoMapper deviceInfoMapper;

    @SneakyThrows
    @Override
    @ServiceActivator(inputChannel = "mqttInputChannel")
    public void handleMessage(Message<?> message) {
        String topic = message.getHeaders().get("mqtt_receivedTopic").toString();
        String payload = message.getPayload().toString();
        // 只处理test/topic主题的消息
//        if ("test/topic".equals(topic)) {
////            try {
////                // 用json序列号反转为Map类型
////                ObjectMapper objectMapper = new ObjectMapper();
////                HashMap hashMap = objectMapper.readValue(payload, HashMap.class);
////                String string = hashMap.get("message").toString();
////                System.out.println(string);
////            } catch (JsonProcessingException e) {
////                throw new RuntimeException(e);
////            }
//            System.out.println("[测试主题处理器] 收到消息 - 内容: " + payload);
//
//            // 这里添加测试主题消息的业务处理逻辑
//        }

        // 转发数据
        // 匹配 +/+/report 模式
//        if (topic.matches("[^/]+/[^/]+/report")){
//            ObjectMapper objectMapper = new ObjectMapper();
//            HashMap hashMap = objectMapper.readValue(payload, HashMap.class);
//            String replace = topic.replace("/report", "/command");
//            mqttMessageService.sendMessage(replace, payload);
//            System.out.println(hashMap.toString());
//        }


        // 接收数据处理
        // 匹配 +/+/report 模式
//        if (topic.matches("[^/]+/submit")){
//            ObjectMapper objectMapper = new ObjectMapper();
//            HashMap hashMap = objectMapper.readValue(payload, HashMap.class);
//
//            // 接收数据，判断数据传输形式
//            String data = (String) hashMap.get("data");
//            if (data.length() < 16){
//                System.out.println("数量小于16" + data.length());
//                return;
//            }
//            // 转换为byte
//            byte[] bytes = Hex.decodeHex(data.toCharArray());
//            System.out.println(data);
//
//        }

        // 设备接收到的转发数据
        // 接收转发
//        if (topic.matches("[^/]+/[^/]+/command")){
//            ObjectMapper objectMapper = new ObjectMapper();
//            HashMap hashMap = objectMapper.readValue(payload, HashMap.class);
//            System.out.println("接收数据:" + hashMap.toString());
//        }


        // 上线与下线
//        if (topic.matches("[^/]+/[^/]+/connect")){
//            ObjectMapper objectMapper = new ObjectMapper();
//            HashMap hashMap = objectMapper.readValue(payload, HashMap.class);
//            System.out.println("连接数据:" + hashMap.toString());
//        }



        // 接收下位机数据更新数据库
        if (topic.matches("[^/]+/submit")) {
            // 获取设备Id
            String hardwareAddressId = topic.split("/")[0].toString();
            // 获取DeviceId
            Integer deviceId = getDeviceId(hardwareAddressId);
            // 获取MQTT的json数据
            HashMap mqttJSON = new ObjectMapper().readValue(payload, HashMap.class);
            // 通过type区分用途
            String type = (String) mqttJSON.get("type");

            // 下位机询问指令
            if (type.equals("get")){
                lowerComputerGet(mqttJSON, deviceId, hardwareAddressId);
            }
            // 下位机设置指令
            else if(type.equals("setData")){
                lowerComputerSet(mqttJSON, deviceId);
            }
            // 下位机定时上传
            else if (type.equals("upload")){
                lowerComputerReply(mqttJSON, deviceId);
            }
        }


        // 设备的连接
        if (topic.matches("[^/]+/connect")){
            // 获取设备Id
            String hardwareAddressId = topic.split("/")[0].toString();
            // 获取DeviceId
            Integer deviceId = getDeviceId(hardwareAddressId);
            // 获取MQTT的json数据
            HashMap mqttJSON = new ObjectMapper().readValue(payload, HashMap.class);
            String stats = (String) mqttJSON.get("stats");
            String iccid = (String) mqttJSON.get("iccid");

            // 设置更新指令
            UpdateWrapper<DeviceInfo> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", deviceId);
            if (stats.equals("true")){
                updateWrapper.set("stats", 1);
            }else {
                updateWrapper.set("stats", 1);
            }

            if (iccid != null){
                updateWrapper.eq("iccid", iccid);
            }
            deviceInfoMapper.update(updateWrapper);
        }
    }

    // 下位机获取指令
    private void lowerComputerGet(HashMap mqttJSON, Integer deviceId, String hardwareAddressId) {
        modbusCommandService.sendGetLowerComputer(deviceId, (String) mqttJSON.get("modbus"), hardwareAddressId);
    }

    // 下位机设置指令
    private void lowerComputerSet(HashMap mqttJSON, Integer deviceId){
        modbusCommandService.sendSetLowerComputer(deviceId, (String) mqttJSON.get("modbus"));
    }

    // 下位机回复指令
    private void lowerComputerReply(HashMap mqttJSON, Integer deviceId){
        String port = (String) mqttJSON.get("port");
        String command = (String) mqttJSON.get("command");
        String modbus = (String) mqttJSON.get("modbus");
        // 更新数据库数据
        modbusCommandService.processModbusResponse(deviceId, command, modbus, port);
    }

    // 获取设备Id
    private Integer getDeviceId(String hardwareAddressId) {
        QueryWrapper<DeviceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("hardware_address", hardwareAddressId);
        DeviceInfo deviceInfo = deviceInfoMapper.selectOne(queryWrapper);
        if (deviceInfo == null){
            return null;
        }
        return deviceInfo.getId();
    }

}
